﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Web;
using System.Web.Security;
using System.Data;
using System.Data.SqlClient;
using ProjectGroep3.ws_Groep3;
using System.Collections;
using MahApps.Metro.Controls;
using ClassLibrary;
using System.Windows.Forms;
using System.Windows.Markup;
using System.Xaml;
using MahApps.Metro.Controls.Dialogs;



namespace ProjectGroep3
{

    public partial class MainWindow : MetroWindow
    {
        private WebService ws = new WebService();
        private DataTable dt, dt2, dtContracts, dt4= new DataTable();
        private DataSet ds = new DataSet();
        private metroMessageDialog mmd = new metroMessageDialog();
        private int companyId;
        private bool confirmation=false;

        // contstructors, methodes
        #region
        //Default Constructor
        public MainWindow()
        {
            InitializeComponent();
        }
        //Construtor met usernaam als parameter
        public MainWindow(String name)
        {
            InitializeComponent();
            startUp(name);
        }
        // Methode om all startupfiles te laden
        private void startUp(String name)
        {
            txtUsername.Text = name;
            txtEmail.Text = Membership.GetUser(name).Email.ToString();
            companyId = ws.getCompanyId(name);
            dt = ws.getCompanyInfo(companyId).Tables[0];

            foreach (DataRow row in dt.Rows)
            {
                txtCompanyId.Text = row["Id"].ToString();
                txtCName.Text = row["name"].ToString();
                txtCAddress.Text = row["Street"].ToString();
                txtCZipcode.Text = row["Zipcode"].ToString();
                txtCEmployees.Text = row["Employees"].ToString();
            }

            dtpReservation.SelectedDate = DateTime.Now;
            dtgReservation.CanUserAddRows = false;
            fillContract(companyId);
            getUsernameReservation(companyId);
        }
        // methode om reservaties te herladen bij datum select
        private void getReservations()
        {
            try
            {
                DateTime selected = dtpReservation.SelectedDate.Value.Date;
                ds = ws.getRegistratie(selected);
                dt2 = ds.Tables[0];
                dtgReservation.ItemsSource = dt2.DefaultView;

                if (dt2.Rows.Count == 0)
                {
                    lblAvailable.Visibility = Visibility.Visible;
                }
                else
                {
                    lblAvailable.Visibility = Visibility.Hidden;
                }
            }
            catch (Exception ex)
            {
                Logging.Log(ex.Message + ex.StackTrace);
                mmd.generateDialog(this, "Error", "More details in the logging file.");
            }
        }
        // methode om geselecteerde room te reserveren
        private void setReservation()
        {
            try
            {                
                if (dtgReservation.SelectedIndex != -1)
                {                   
                    DateTime start = dtpReservation.SelectedDate.Value.Date;
                    DateTime end = start.AddHours(23).AddMinutes(59).AddSeconds(59);             
                    int companyID = Convert.ToInt32(txtCompanyId.Text);

                    if (start.Date >= DateTime.Now.Date)
                    {                     
                        DataRowView drv = (DataRowView)dtgReservation.SelectedItem;
                        string room = drv[0].ToString();

                        int newReservationId = ws.insertReservation(start, end, companyID, room);

                        if (newReservationId > 1)
                        {
                            mmd.generateDialog(this, "Succes", room + " planned.");
                            try
                            {
                                //aanmaak reservatie loggen, event = 1 betekent creatie
                                ws.eventReservation(1, txtUsername.Text, room, start);
                            }
                            catch (Exception ex)
                            {
                                Logging.Log(ex.Message + ex.StackTrace);
                                mmd.generateDialog(this, "Error", "More details in the logging file.");
                            }
                            getReservations();
                            getUsernameReservation(companyId);
                        }
                    }
                    else mmd.generateDialog(this, "Error", "Rooms must be booked with 1 day notice and can't be in the past.");
                }
                else mmd.generateDialog(this, "Error", "No Rooms Selected.");
            }
            catch (Exception ex)
            {
                Logging.Log(ex.Message + ex.StackTrace);
                mmd.generateDialog(this, "Error", "More details in the logging file.");
            }

        }
        // haalt de huidige contracten van een bedrijf op
        private void fillContract(int companyId)    
        {
            try
            {
                dtContracts = ws.getContractsByCompayId(companyId).Tables[0];

                if (dtContracts.Rows.Count != 0)
                {
                    DateTime startDate = Convert.ToDateTime(dtContracts.Rows[0]["StartDate"]);
                    DateTime endDate = Convert.ToDateTime(dtContracts.Rows[0]["EndDate"]);
                    txtDescription.Text = Convert.ToString(dtContracts.Rows[0]["Description"]);
                    txtStart.Text = Convert.ToString(startDate.Date);
                    txtEnd.Text = Convert.ToString(endDate.Date);
                    txtPrice.Text = Convert.ToString(dtContracts.Rows[0]["Price"]);
                }
                else
                {
                    txtDescription.Text = "No contracts available.";
                }
            }
            catch (Exception ex)
            {
                Logging.Log(ex.Message + ex.StackTrace);
                mmd.generateDialog(this, "Error", "More details in the logging file.");
            }


        }
        private void getUsernameReservation(int companyId)
        {
            try
            {
                dt4 = ws.getUsernameReservation(companyId).Tables[0];
                dtgDeleteReservations.ItemsSource = dt4.DefaultView;
            }
            catch (Exception ex)
            {
                Logging.Log(ex.Message + ex.StackTrace);
                mmd.generateDialog(this, "Error", "More details in the logging file.");
            }


        }

        
        public async void removeReservation()
        {
            try
            {
                if (dtgDeleteReservations.SelectedIndex != -1)
                {
                    DataRowView drv = (DataRowView)dtgDeleteReservations.SelectedItem;
                    int id = Convert.ToInt32(drv[0]);
                    DateTime reservationTime = Convert.ToDateTime(drv[1]);
                    string locationName = drv[2].ToString();
                    await generateConfirmation(this, "Are you sure you want to delete?");



                    if (confirmation == true)
                    {
                        mmd.generateDialog(this, "Succes", locationName + " removed.");
                        ws.deleteReservation(id);
                        try
                        {
                            //verwijderen reservatie loggen, event = 0 betekent verwijderen
                            ws.eventReservation(0, txtUsername.Text, locationName, reservationTime);
                        }
                        catch (Exception ex)
                        {
                            Logging.Log(ex.Message + ex.StackTrace);
                            mmd.generateDialog(this, "Error", "More details in the logging file.");
                        }
                        getUsernameReservation(companyId);
                        getReservations();
                    }
                }
                else mmd.generateDialog(this, "", "No booking selected.");
            }
            catch (Exception ex)
            {
                Logging.Log(ex.Message + ex.StackTrace);
                mmd.generateDialog(this, "Error", "More details in the logging file.");
            }
        }


        
        #endregion

        // interactie met interface
        #region
        private void dtpReservation_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            getReservations();
        }

        private void btnBook_Click(object sender, RoutedEventArgs e)
        {
            setReservation();
        }

       
        private void image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Login login = new Login();
            login.Show();
            this.Close();
        }
        public void btnCancelContract_Click(object sender, RoutedEventArgs e)
        {
            int Id = Convert.ToInt32(dtContracts.Rows[0]["Id"]);
            cancelContract(Id);  
            fillContract(Convert.ToInt32(txtCompanyId.Text));
        }

        public async void cancelContract(int Id)
        {
            try
            {
                await generateConfirmation(this, "Are you sure you want to cancel your company's contract?");

                if (confirmation == true)
                {
                    if (ws.cancelContract(Id))
                    {
                        mmd.generateDialog(this, "Succes" ,"Contract succesfully cancelled.");
                    }
                    else
                    {
                        mmd.generateDialog(this, "Oops", "Something went wrong, cancelling contract failed."); 
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Log(ex.Message + ex.StackTrace);
                mmd.generateDialog(this, "Error", "More details in the logging file.");
            }
            
        }
       

        private void btnDeleteReservation_Click(object sender, RoutedEventArgs e)
        {
            removeReservation();
        }

        public async Task generateConfirmation(MetroWindow handle, string message)
        {
            MessageDialogResult result = await handle.ShowMessageAsync(message, "", MessageDialogStyle.AffirmativeAndNegative);
            if (result == MessageDialogResult.Affirmative)
            {
                confirmation = true;

            }
            else
            {
                confirmation = false;
            }




        }
        #endregion

        

    }
}
